package com.iwinding.ladygg.ui.act;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.iwinding.ladygg.R;
import com.iwinding.ladygg.constant.Constant;
import com.iwinding.ladygg.constant.SPConstant;
import com.iwinding.ladygg.event.FinshLoginEvent;
import com.iwinding.ladygg.net.RequestManager;
import com.iwinding.ladygg.net.callback.BaseRpCallback;
import com.iwinding.ladygg.net.callback.CaptchaCallback;
import com.iwinding.ladygg.net.request.BindingMobileReq;
import com.iwinding.ladygg.net.request.CaptchaReq;
import com.iwinding.ladygg.net.response.BaseRopnse;
import com.iwinding.ladygg.net.response.CaptchaRp;
import com.iwinding.ladygg.net.response.ThirdPartyLoginRp;
import com.iwinding.ladygg.utils.GsonUtil;
import com.iwinding.ladygg.utils.SPUtils;
import com.iwinding.ladygg.utils.StringUtil;
import com.iwinding.ladygg.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

/**
 * Created by hezhiyong on 2017/3/31.
 */

public class BindPhoneActivity extends BaseActivity implements View.OnClickListener {


    private AutoCompleteTextView mEtPhone;
    private AutoCompleteTextView mEtVercode;
    private AutoCompleteTextView mEtPassword;

    private ImageView mImgCleanPhone;
    private ImageView mImgCleanPassword;
    private ImageView mImgCleanVercode;
    private Button mBtnSendVercode;
    private Button mBtnReSendVercode;
    private ImageView mImgSecure;
    private ImageView mImgVisable;

    private Button mBtnConfirm;

    private Timer mTimer = null;

    @Override
    protected int getLayoutID() {
        return R.layout.icane_activity_bindphone;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBackTxtResId(R.string.icane_user_login);
        setRightTxtResId(R.string.icane_skip);
        setTitleResId(R.string.icane_bindphone);
        initView();
        setListener();
    }

    void initView() {
        //如果不是第三方的直接强退
        if(!(mOAAplication.getmLoginRp() instanceof ThirdPartyLoginRp)){
            startActivity(new Intent(mContext,MainActivity.class));
            finish();
            return;
        }
        mEtPhone = (AutoCompleteTextView) findViewById(R.id.icane_edit_bindphone);
        mEtVercode = (AutoCompleteTextView) findViewById(R.id.icane_edit_vercode);
        mEtPassword = (AutoCompleteTextView) findViewById(R.id.icane_setting_password);

        mImgCleanPhone = (ImageView) findViewById(R.id.clear_phone);
        mImgCleanPassword = (ImageView) findViewById(R.id.clear_password);
        mImgCleanVercode = (ImageView) findViewById(R.id.clear_vercode);
        mImgSecure = (ImageView) findViewById(R.id.icane_secure);
        mImgVisable = (ImageView) findViewById(R.id.icane_visable);

        mBtnSendVercode = (Button) findViewById(R.id.send_ver);
        mBtnReSendVercode = (Button) findViewById(R.id.resend_ver);
        mBtnConfirm = (Button) findViewById(R.id.icane_confirm);


    }

    void setListener() {
        mEtPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mImgCleanPhone.setVisibility(s.length() == 0 ? View.GONE : View.VISIBLE);
            }
        });
        mEtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mImgCleanPassword.setVisibility(s.length() == 0 ? View.GONE : View.VISIBLE);
            }
        });
        mEtVercode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mImgCleanVercode.setVisibility(s.length() == 0 ? View.GONE : View.VISIBLE);
            }
        });

        mImgCleanPhone.setOnClickListener(this);
        mImgCleanPassword.setOnClickListener(this);
        mImgSecure.setOnClickListener(this);
        mImgVisable.setOnClickListener(this);
        mBtnSendVercode.setOnClickListener(this);
        mBtnReSendVercode.setOnClickListener(this);
        mBtnConfirm.setOnClickListener(this);

        mRightTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, MainActivity.class));
                EventBus.getDefault().post(new FinshLoginEvent());
                finish();
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.clear_phone:
                mEtPhone.setText("");
                break;
            case R.id.clear_vercode:
                mEtVercode.setText("");
                break;
            case R.id.clear_password:
                mEtPassword.setText("");
                break;
            case R.id.icane_secure:
                mImgSecure.setVisibility(View.GONE);
                mImgVisable.setVisibility(View.VISIBLE);
                //默认状态显示密码--设置文本 要一起写才能起作用  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
//                String pw =  mEtPassword.getText().toString();
//                mEtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
//                mEtPassword.setText(pw);
                mEtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                mEtPassword.setSelection(mEtPassword.getText().length());
                break;
            case R.id.icane_visable:
                mImgVisable.setVisibility(View.GONE);
                mImgSecure.setVisibility(View.VISIBLE);
//                String pwSecure =  mEtPassword.getText().toString();
//                mEtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
//                mEtPassword.setText(pwSecure);
                mEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                mEtPassword.setSelection(mEtPassword.getText().length());
                break;
            case R.id.send_ver:
                sendVercode();
                break;
            case R.id.resend_ver:
//                sendVercode();
                break;
            case R.id.icane_confirm:
                bindPhone();
                break;
//            case R.id.icane_user_foreigner_register:
//                Intent intent = new Intent(this, AbroadRegisterActivity.class);
//                startActivity(intent);
//                break;
        }
    }

    /**
     * 发送验证码
     */
    private void sendVercode() {
        mBtnSendVercode.setEnabled(false);
        String phone = mEtPhone.getEditableText().toString();
        if (!TextUtils.isEmpty(phone)) {
            if (!StringUtil.isMobileNO(phone)) {
                ToastUtil.openMolieErrorToast(this);
                mBtnSendVercode.setEnabled(true);
                return;
            }
            //发送短信验证码
//            String requestTag = String.valueOf(System.currentTimeMillis());
            CaptchaReq req = new CaptchaReq();
            req.mobile = phone;
            RequestManager.postBindingMobileCaptcha(mContext, req, new CaptchaCallback(BindPhoneActivity.this) {

                @Override
                public void onResult(CaptchaRp captchaRp) {
                    if (captchaRp == null) {
                        return;
                    }
                    mBtnSendVercode.setEnabled(true);
                    mBtnSendVercode.setText(R.string.resend_verification);

                    mBtnSendVercode.setVisibility(View.GONE);
                    setVerTimerTask();
                    mBtnReSendVercode.setVisibility(View.VISIBLE);
                }

                @Override
                public void onFail(String errorMsg) {
                    ToastUtil.openBaseToast(BindPhoneActivity.this, errorMsg, Toast.LENGTH_SHORT);
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    ToastUtil.openVerFailToast(BindPhoneActivity.this);
                    mBtnSendVercode.setEnabled(true);
                }
            });
        }
    }

    /**
     * 注册
     */
    void bindPhone() {
        final BindingMobileReq bindingMobileReq = new BindingMobileReq();
        String phone = mEtPhone.getEditableText().toString();
        String vercode = mEtVercode.getEditableText().toString();
        String pw = mEtPassword.getEditableText().toString();
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.openEmptyPhone(this);
            return;
        }
        if (!StringUtil.isMobileNO(phone)) {
            ToastUtil.openMolieErrorToast(this);
            mBtnSendVercode.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(vercode)) {
            ToastUtil.openEmptyVer(this);
            return;
        }
        if (TextUtils.isEmpty(pw)) {
            ToastUtil.openEmptyPw(this);
            return;
        }
        bindingMobileReq.mobile = phone;
        bindingMobileReq.captcha = vercode;
        bindingMobileReq.password = pw;
        String weiboToken = ((ThirdPartyLoginRp) mOAAplication.getmLoginRp()).weiboToken;
        String qqToken = ((ThirdPartyLoginRp) mOAAplication.getmLoginRp()).qqToken;
        bindingMobileReq.openId = TextUtils.isEmpty(weiboToken) ? qqToken : weiboToken;

        RequestManager.postBindingMobile(mContext, bindingMobileReq, new BaseRpCallback<BaseRopnse>() {

            @Override
            public BaseRopnse parseResponse(BaseRopnse response, int id) {
                return response;
            }

            @Override
            public void onResult(BaseRopnse captchaRp) {
                ThirdPartyLoginRp thirdPartyLoginRp = (ThirdPartyLoginRp) mOAAplication.getmLoginRp();
                thirdPartyLoginRp.mobile = bindingMobileReq.mobile;
                thirdPartyLoginRp.passwrod = bindingMobileReq.password;
                thirdPartyLoginRp.isBindingPhone = "1";
                SPUtils.putSpProperty(mContext, SPConstant.LOGIN_USER, GsonUtil.getInstance().toJson(thirdPartyLoginRp));
                mOAAplication.setmLoginRp(thirdPartyLoginRp);
                startActivity(new Intent(mContext, MainActivity.class));
                EventBus.getDefault().post(new FinshLoginEvent());
                finish();
            }

            @Override
            public void onFail(String errorMsg) {
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
            }
        });
    }

    private TimerTask verTimerTask = null;

    private void setVerTimerTask() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer.purge();
            mTimer = null;
            verTimerTask = null;
        }

        mTimer = new Timer();
        verTimerTask = new SMSTimerTask();

        mTimer.schedule(verTimerTask, 0);
        mBtnReSendVercode.setVisibility(View.VISIBLE);
        mBtnSendVercode.setVisibility(View.GONE);
    }

    class SMSTimerTask extends TimerTask {
        @Override
        public void run() {
            for (int i = Constant.TimeConstant.VER_COUNTDOWN; i > 0; i--) {
                myHandler.sendEmptyMessage(i);
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {

                }
            }
            myHandler.sendEmptyMessage(0);
        }
    }

    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what != 0) {
                mBtnReSendVercode.setText(String.format(getString(R.string.resend_verification_second), msg.what));
            } else {
                mBtnReSendVercode.setVisibility(View.GONE);
                mBtnSendVercode.setVisibility(View.VISIBLE);
            }
        }
    };


}
